package com.lkd.handler;

import com.google.common.base.Strings;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @Author FJL
 * @Description TODO
 * @Date 2022/8/29 15:42
 **/
@Component
@Topic("TopicConfig.VMS_SUPPLY_TOPIC")
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        // 将json字符串解析成supplyContract
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        // 参数校验
        if(supplyContract==null) return;

        // 找到指派人
        // 找到设备所在区域负责人员中最少工单量人员
        VmVO vm = vmService.getVMInfo(supplyContract.getInnerCode());
        if(vm==null) return;
        Integer userId = taskService.getLeastTask(vm.getRegionId(), false);
        if(userId==0)return;

        // 创建补货工单
        TaskViewModel taskViewModel = new TaskViewModel();

        taskViewModel.setDesc("自动补货工单");
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setUserId(userId);
        taskViewModel.setCreateType(0);
        taskViewModel.setAssignorId(0);
        taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(e->{
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            BeanUtils.copyProperties(e,taskDetailsViewModel);
            taskDetailsViewModel.setChannelCode(e.getChannelId());
            taskDetailsViewModel.setExpectCapacity(e.getCapacity());
            return taskDetailsViewModel;
        }).collect(Collectors.toList()));

        taskService.createTask(taskViewModel);



    }
}
